package com.hengpeng.itfin.service.activity.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfin.common.MessageUtil;
import com.hengpeng.itfin.service.activity.RedPacketService;
import com.hengpeng.itfin.service.impl.BaseServiceImpl;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.en.ActivityStatus;
import com.hengpeng.itfinbase.en.RewardLevel;
import com.hengpeng.itfinbase.en.RewardRedPacketStatus;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.activity.CreateShareRedPacketRequest;
import com.hengpeng.itfinbase.message.activity.CreateShareRedPacketResponse;
import com.hengpeng.itfinbase.message.activity.InvestRedPacketRequest;
import com.hengpeng.itfinbase.message.activity.InviteSendRedPacketRequest;
import com.hengpeng.itfinbase.message.activity.RegisterSendRedPacketRequest;
import com.hengpeng.itfinbase.message.activity.UnfreeRedPacketRequest;
import com.hengpeng.itfinbase.persist.Activity;
import com.hengpeng.itfinbase.persist.Reward;
import com.hengpeng.itfinbase.persist.RewardRedPacketShareLog;
import com.hengpeng.itfinbase.persist.RewardRedpacket;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserRefer;

public class RedPacketServiceImpl extends BaseServiceImpl implements RedPacketService {

    private static final Log logger = LogFactory.getLog(RedPacketServiceImpl.class);

    @Override
    public ResponseMessage registerSendRedPacket(RegisterSendRedPacketRequest request) {
        /**
         * <pre>
         * 1,判断当前活动是否可用 
         * 2,向当前注册用户发放注册红包
         * </pre>
         */
        if (request.getUserId() == null || request.getActivityType() == null) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class,
                    RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
        }
        Activity activity = daoFactory.getActivityDao().getActivityByType(request.getActivityType());
        if (activity.getStatus() != ActivityStatus.ACTIVE) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class, RespCodeConstants.CommonCode.TRANS_FAIL,
                    "活动已暂停或还未开始");
        }
        UserInfo userInfo = daoFactory.getUserInfoDao().get(request.getUserId());
        Reward reward = null;
        Set<Reward> rewardset = activity.getRewards();
        Iterator<Reward> iteRewards = rewardset.iterator();
        while (iteRewards.hasNext()) {
            reward = iteRewards.next();
        }
        if (reward == null) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class, RespCodeConstants.CommonCode.TRANS_FAIL,
                    "活动[activityid=" + activity.getId() + "]奖品信息配置错误,请检查");
        }
        RewardRedpacket redpacket = new RewardRedpacket();
        redpacket.setActiveid(activity.getId());
        redpacket.setRewardId(reward.getId());
        redpacket.setUserId(userInfo.getId());
        redpacket.setUserName(userInfo.getUserName());
        redpacket.setTrustAccountId(userInfo.getTrustAccountId());
        redpacket.setMoney(Long.parseLong(reward.getRewardVal()));
        redpacket.setGettime(new Date());
        redpacket.setEndtime(DateTimeUtil.addDate(new Date(), reward.getDeadLine()));
        redpacket.setCreateTime(new Date());
        redpacket.setStatus(RewardRedPacketStatus.CANUSE);
        redpacket.setUpdateTime(new Date());
        redpacket = daoFactory.getRedPacketDao().save(redpacket);
        if (redpacket.getId() == null) {
            logger.error("注册红包发放失败！用户[id=" + userInfo.getId() + "][红包面额=" + reward.getRewardVal() + "][红包类型=REGISTER]");
        }
        return MessageUtil.GetSuccessMessage();
    }

    @Override
    public ResponseMessage investSendRedPacket(InvestRedPacketRequest request) {
        if (request.getUserId() == null || request.getActivityType() == null || request.getRewardVal() == null) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class,
                    RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
        }
        Activity activity = daoFactory.getActivityDao().getActivityByType(request.getActivityType());
        if (activity.getStatus() != ActivityStatus.ACTIVE) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class, RespCodeConstants.CommonCode.TRANS_FAIL,
                    "活动已暂停或还未开始");
        }

        UserInfo userInfo = daoFactory.getUserInfoDao().get(request.getUserId());
        Reward reward = null;
        Set<Reward> rewardset = activity.getRewards();
        Iterator<Reward> iteRewards = rewardset.iterator();
        while (iteRewards.hasNext()) {
            reward = iteRewards.next();
        }
        if (reward == null) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class, RespCodeConstants.CommonCode.TRANS_FAIL,
                    "活动[activityid=" + activity.getId() + "]奖品信息配置错误,请检查");
        }
        RewardRedpacket redpacket = new RewardRedpacket();
        redpacket.setActiveid(activity.getId());
        redpacket.setRewardId(reward.getId());
        redpacket.setCreateTime(new Date());
        redpacket.setEndtime(DateTimeUtil.addDate(new Date(), reward.getDeadLine()));
        redpacket.setGettime(new Date());
        redpacket.setMoney(request.getRewardVal());
        redpacket.setStatus(RewardRedPacketStatus.CANUSE);
        redpacket.setTrustAccountId(userInfo.getTrustAccountId());
        redpacket.setUpdateTime(new Date());
        redpacket.setUserId(userInfo.getId());
        redpacket.setUserName(userInfo.getUserName());
        redpacket = daoFactory.getRedPacketDao().save(redpacket);
        if (redpacket.getId() == null) {
            logger.error("投资等额红包发放失败！用户[id=" + userInfo.getId() + "][红包面额=" + request.getRewardVal() + "][红包类型=INVEST]");
        }
        return MessageUtil.GetSuccessMessage();
    }

    @Override
    public ResponseMessage inviteSendRedPacket(InviteSendRedPacketRequest request) {
        /**
         * <pre>
         * 1,判断当前活动是否可用
         * 2,向当前注册人的推荐人发放红包
         * </pre>
         */
        if (request.getUserId() == null || request.getActivityType() == null) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class,
                    RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
        }
        Activity activity = daoFactory.getActivityDao().getActivityByType(request.getActivityType());
        if (activity.getStatus() != ActivityStatus.ACTIVE) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class, RespCodeConstants.CommonCode.TRANS_FAIL,
                    "活动已暂停或还未开始");
        }
        Reward levelone = null, leveltwo = null, levelthree = null;
        Set<Reward> rewards = activity.getRewards();
        Iterator<Reward> iteRewards = rewards.iterator();
        while (iteRewards.hasNext()) {
            Reward r = iteRewards.next();
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELONE) {
                levelone = r;
            }
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELTWO) {
                leveltwo = r;
            }
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELTHREE) {
                levelthree = r;
            }
        }
        if (levelone == null || leveltwo == null || levelthree == null) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class, RespCodeConstants.CommonCode.TRANS_FAIL,
                    "活动[activityid=" + activity.getId() + "]奖品信息配置错误,请检查");
        }
        /**
         * 第一层推荐用户
         */
        UserRefer leveOneUserRefer = daoFactory.getUserReferDao().getUserReferByToUserId(request.getUserId());
        if (leveOneUserRefer != null) {
            UserInfo leveOneUserInfo = daoFactory.getUserInfoDao().get(leveOneUserRefer.getFromUserId());
            RewardRedpacket leveOneRedpacket = new RewardRedpacket();
            leveOneRedpacket.setActiveid(activity.getId());
            leveOneRedpacket.setRewardId(levelone.getId());
            leveOneRedpacket.setCreateTime(new Date());
            leveOneRedpacket.setEndtime(DateTimeUtil.addDate(new Date(), levelone.getDeadLine()));
            leveOneRedpacket.setGettime(new Date());
            leveOneRedpacket.setMoney(Long.parseLong(levelone.getRewardVal()));
            leveOneRedpacket.setStatus(RewardRedPacketStatus.CANUSE);
            leveOneRedpacket.setTrustAccountId(leveOneUserInfo.getTrustAccountId());
            leveOneRedpacket.setUpdateTime(new Date());
            leveOneRedpacket.setUserId(leveOneUserInfo.getId());
            leveOneRedpacket.setUserName(leveOneUserInfo.getUserName());
            leveOneRedpacket = daoFactory.getRedPacketDao().save(leveOneRedpacket);
            if (leveOneRedpacket.getId() == null) {
                logger.error("邀请注册红包发放失败！用户[id=" + leveOneUserInfo.getId() + "][红包面额=" + levelone.getRewardVal()
                        + "][红包类型=INVITE]");
            }
            /**
             * 第二层推荐用户
             */
            UserRefer leveTwoUserRefer = daoFactory.getUserReferDao().getUserReferByToUserId(leveOneUserInfo.getId());
            if (leveTwoUserRefer != null) {
                UserInfo leveTwoUserInfo = daoFactory.getUserInfoDao().get(leveTwoUserRefer.getFromUserId());
                RewardRedpacket leveTwoRedpacket = new RewardRedpacket();
                leveTwoRedpacket.setActiveid(activity.getId());
                leveTwoRedpacket.setRewardId(leveltwo.getId());
                leveTwoRedpacket.setCreateTime(new Date());
                leveTwoRedpacket.setEndtime(DateTimeUtil.addDate(new Date(), leveltwo.getDeadLine()));
                leveTwoRedpacket.setGettime(new Date());
                leveTwoRedpacket.setMoney(Long.parseLong(leveltwo.getRewardVal()));
                leveTwoRedpacket.setStatus(RewardRedPacketStatus.CANUSE);
                leveTwoRedpacket.setTrustAccountId(leveTwoUserInfo.getTrustAccountId());
                leveTwoRedpacket.setUpdateTime(new Date());
                leveTwoRedpacket.setUserId(leveTwoUserInfo.getId());
                leveTwoRedpacket.setUserName(leveTwoUserInfo.getUserName());
                leveTwoRedpacket = daoFactory.getRedPacketDao().save(leveTwoRedpacket);
                if (leveTwoRedpacket.getId() == null) {
                    logger.error("邀请注册红包发放失败！用户[id=" + leveTwoUserInfo.getId() + "][红包面额=" + leveltwo.getRewardVal()
                            + "][红包类型=INVITE]");
                }
                /**
                 * 第三层推荐用户
                 */
                UserRefer leveThreeUserRefer = daoFactory.getUserReferDao().getUserReferByToUserId(
                        leveTwoUserInfo.getId());
                if (leveThreeUserRefer != null) {
                    UserInfo leveThreeUserInfo = daoFactory.getUserInfoDao().get(leveThreeUserRefer.getFromUserId());
                    RewardRedpacket leveThreeRedpacket = new RewardRedpacket();
                    leveThreeRedpacket.setActiveid(activity.getId());
                    leveThreeRedpacket.setRewardId(levelthree.getId());
                    leveThreeRedpacket.setCreateTime(new Date());
                    leveThreeRedpacket.setEndtime(DateTimeUtil.addDate(new Date(), levelthree.getDeadLine()));
                    leveThreeRedpacket.setGettime(new Date());
                    leveThreeRedpacket.setMoney(Long.parseLong(levelthree.getRewardVal()));
                    leveThreeRedpacket.setStatus(RewardRedPacketStatus.CANUSE);
                    leveThreeRedpacket.setTrustAccountId(leveThreeUserInfo.getTrustAccountId());
                    leveThreeRedpacket.setUpdateTime(new Date());
                    leveThreeRedpacket.setUserId(leveThreeUserInfo.getId());
                    leveThreeRedpacket.setUserName(leveThreeUserInfo.getUserName());
                    leveThreeRedpacket = daoFactory.getRedPacketDao().save(leveThreeRedpacket);
                    if (leveThreeRedpacket.getId() == null) {
                        logger.error("邀请注册红包发放失败！用户[id=" + leveThreeUserInfo.getId() + "][红包面额="
                                + levelthree.getRewardVal() + "][红包类型=INVITE]");
                    }
                }
            }
        }
        return MessageUtil.GetSuccessMessage();
    }

    @Override
    public ResponseMessage unFreeRedPacket(UnfreeRedPacketRequest request) {
        if (StringHelper.isEmpty(request.getMobile()) || request.getUserId() == null) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class,
                    RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
        }
        List<RewardRedpacket> dataList = daoFactory.getRedPacketDao().findRedPacketByStatusAndUser(
                RewardRedPacketStatus.UNACTIVE, request.getMobile());
        if (dataList != null) {
            for (RewardRedpacket red : dataList) {
                red.setUserId(request.getUserId());
                red.setTrustAccountId(request.getTrustAccountId());
                red.setStatus(RewardRedPacketStatus.CANUSE);
                red.setUpdateTime(new Date());
            }
            daoFactory.getRedPacketDao().updateAll(dataList);
        }
        return MessageUtil.GetSuccessMessage();
    }

    @Override
    public ResponseMessage createShareRedPacket(CreateShareRedPacketRequest request) {
        if (StringHelper.isEmpty(request.getMobile()) || request.getActivityType() == null
                || request.getHostRedPacketId() == null ||  request.getRewardId() == null) {
            return MessageUtil.getErrorResponseMessage(CreateShareRedPacketResponse.class,
                    RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
        }
        Activity activity = daoFactory.getActivityDao().getActivityByType(request.getActivityType());
        if (activity.getStatus() != ActivityStatus.ACTIVE) {
            return MessageUtil.getErrorResponseMessage(CreateShareRedPacketResponse.class, RespCodeConstants.CommonCode.TRANS_FAIL,
                    "活动已暂停或还未开始");
        }
        /**
         * <pre>
         * 1,乐观锁更新原红包值
         * 2,生成新的红包记录
         * 3,手机号码校验当前用户是否已在本平台注册，已注册红包状态就是可用，未注册红包状态就是未激活红包
         * 4,生成红包分享记录
         * 5,判断当前被分享的红包面值是否为0如果为0,则更新红包状态为：已分享
         * </pre>
         */
        RewardRedpacket fromRedpacket = serviceFactory.getDaoFactory().getRedPacketDao().get(request.getHostRedPacketId());//获取分享者要分享的红包
        Reward reward = serviceFactory.getDaoFactory().getRewardDao().get(request.getRewardId());//获取对应奖品
        int i = serviceFactory.getDaoFactory().getRedPacketDao().shareUpdateRedPacket(fromRedpacket.getId(), Long.parseLong(reward.getRewardVal()), RewardRedPacketStatus.CANUSE, new Date());
        if (i > 0) {
            RewardRedpacket newRedpacket = new RewardRedpacket();
            newRedpacket.setActiveid(activity.getId());
            newRedpacket.setRewardId(request.getRewardId());
            newRedpacket.setCreateTime(new Date());
            newRedpacket.setEndtime(DateTimeUtil.addDate(new Date(), reward.getDeadLine()));
            newRedpacket.setGettime(new Date());
            newRedpacket.setMoney(Long.parseLong(reward.getRewardVal()));
            newRedpacket.setUpdateTime(new Date());
            UserInfo userInfo = serviceFactory.getDaoFactory().getUserInfoDao().getUserByMobile(request.getMobile());
            if (userInfo != null) {//用户已在本平台注册
                newRedpacket.setStatus(RewardRedPacketStatus.CANUSE);
                newRedpacket.setTrustAccountId(userInfo.getTrustAccountId());
                newRedpacket.setUserId(userInfo.getId());
                newRedpacket.setUserName(userInfo.getUserName());
            } else {//用户没有在本平台注册
                newRedpacket.setStatus(RewardRedPacketStatus.UNACTIVE);//未激活状态
                newRedpacket.setTrustAccountId(null);
                newRedpacket.setUserId(null);
                newRedpacket.setUserName(null);
            }
            newRedpacket = daoFactory.getRedPacketDao().save(newRedpacket);
            if (newRedpacket.getId() == null) {//失败回退
                logger.error("用户[mobile=" + request.getMobile() + "]领取红包失败,[红包面额="
                        + (Long.parseLong(reward.getRewardVal())/100) + "][红包类型="+reward.getRewardType()+"]");
                serviceFactory.getDaoFactory().getRedPacketDao().shareBackUpdateRedPacket(fromRedpacket.getId(), Long.parseLong(reward.getRewardVal()), RewardRedPacketStatus.CANUSE, new Date());
                return MessageUtil.getErrorResponseMessage(ResponseMessage.class, RespCodeConstants.CommonCode.TRANS_FAIL, RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
            } else {//成功,生成红包分享记录,判断被分享的红包是否已经完全被分享掉
                RewardRedPacketShareLog shareLog = new RewardRedPacketShareLog();
                shareLog.setCreateTime(new Date());
                shareLog.setFromRedPacketId(fromRedpacket.getId());
                shareLog.setFromUserId(fromRedpacket.getUserId());
                shareLog.setMoney(Long.parseLong(reward.getRewardVal()));
                shareLog.setNewRedPacketId(newRedpacket.getId());
                shareLog.setNewRedPacketOwnerMobile(request.getMobile());
                shareLog.setTransTime(new Date());
                shareLog.setUpdateTime(new Date());
                serviceFactory.getDaoFactory().getCommonDao().saveEntity(shareLog);
                /**
                 * 
                 */
            }
        }
        return MessageUtil.GetSuccessMessage();
    }
}